<?php
// +----------------------------------------------------------------------
// | KITEGO-Admin「开箱即用」「人人全栈」
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2024 https://www.kitego.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed KITEGO并不是自由软件，未经许可不能去掉KITEGO相关版权
// +----------------------------------------------------------------------
// | Author: KITEGO Team <bd@kitego.cn>
// +----------------------------------------------------------------------

namespace oauth\impl;

use oauth\OAuthBase;
use GuzzleHttp\Client;

class GiteeImpl extends OAuthBase
{
    private $clientId;
    private $clientSecret;
    private $redirectUri;
    private $apiBaseUrl = 'https://gitee.com/api/v5';

    private $client;

    public function __construct($params)
    {
        $this->clientId = $params['clientId'];
        $this->clientSecret = $params['clientSecret'];
        $this->redirectUri = $params['redirectUri'];

        $this->client = new Client();
    }

    public function getAuthorizationUri(): string
    {
        $params = [
            'client_id' => $this->clientId,
            'redirect_uri' => $this->redirectUri,
            'response_type' => 'code',
            'scope' => 'user_info projects'
        ];

        return 'https://gitee.com/oauth/authorize?' . http_build_query($params);
    }

    public function getAccessToken($code): string
    {
        $response = $this->client->post("https://gitee.com/oauth/token", [
            'form_params' => [
                'grant_type' => 'authorization_code',
                'client_id' => $this->clientId,
                'client_secret' => $this->clientSecret,
                'code' => $code,
                'redirect_uri' => $this->redirectUri
            ]
        ]);

        $result = json_decode($response->getBody(), true);

        if (!isset($result['access_token'])) exception('access_token 获取失败');

        return $result['access_token'];
    }

    /**
     * 获取用户信息
     */
    public function getUserInfo(string $accessToken): array
    {
        $url = "{$this->apiBaseUrl}/user";

        $response = $this->client->get($url, [
            'headers' => [
                'Authorization' => "Bearer {$accessToken}"
            ]
        ]);

        $res = json_decode($response->getBody(), true);

        kg_file_put_contents('giteeImpl', [
            $url,
            json_encode($res, 256),
        ]);

        return $res;
    }

    public function forkGiteeRepository($accessToken, $owner, $repo)
    {
        $url = "{$this->apiBaseUrl}/repos/{$owner}/{$repo}/forks";

        try {
            $response = $this->client->post($url, [
                'headers' => [
                    'Authorization' => "Bearer {$accessToken}"
                ]
            ]);

            return json_decode($response->getBody(), true);
        } catch (\Exception $e) {
            kg_file_put_contents('giteeImpl', [
                $url,
                $e->getMessage(),
            ]);
        }
    }

    public function followUser($accessToken, $username)
    {
        $url = "{$this->apiBaseUrl}/user/following/{$username}";

        try {
            $response = $this->client->put($url, [
                'headers' => [
                    'Authorization' => "Bearer {$accessToken}"
                ]
            ]);

            return json_decode($response->getBody(), true);
        } catch (\Exception $e) {
            kg_file_put_contents('giteeImpl', [
                $url,
                $e->getMessage(),
            ]);
        }
    }
}